package chapter2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by uu on 2017/6/14.
 */
public class Demo2_Hello_World_Consumer extends DefaultConsumer{
    public Demo2_Hello_World_Consumer(Channel channel) {
        super(channel);
    }

    public static void main(String[] args){
        boolean autoAck = false;
        ConnectionFactory factory =  new  ConnectionFactory();
        factory.setHost("localhost");
        try {
            //建立到服务器连接
            Connection connection = factory.newConnection();
            //获得信道
            final Channel channel = connection.createChannel();
            channel.basicConsume("demo1_queue", autoAck, "myConsumerTag",
                    new DefaultConsumer(channel) {
                     @Override
                        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException
                        {
                            String routingKey = envelope.getRoutingKey();
                            String contentType = properties.getContentType();
                            long deliveryTag = envelope.getDeliveryTag();
                            // (process the message csomponents here ...)
                            System.out.println(new String(body, "UTF-8"));
                            channel.basicAck(deliveryTag, false);
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
